<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Social_login {
    private $CI;
    public function __construct() {
        //parent::__construct();
        $this->CI =& get_instance();
    }
    
    public function google_login_validate( $google_user ){  
        $email = $google_user['openid_ext1_value_email'];
        $this->CI->load->library('ion_auth');
        $this->CI->load->model('user_model');
        //require_once(APPPATH.'libraries/Ion_auth.php');
        if($this->CI->ion_auth->email_check($email)){
            $this->CI->ion_auth->trigger_events('pre_login');
            $user = $this->CI->user_model->get_user_by_email( $email );         
            $this->CI->ion_auth->set_session($user);
            $this->CI->ion_auth->update_last_login($user->id);
            $this->CI->ion_auth->clear_login_attempts($email);
            $this->CI->ion_auth->trigger_events(array('post_login', 'post_login_successful')); 
        }
        else{
            $username = strtolower($email);
            $email    = strtolower($email);
            $password = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 6)), 0, 6);

            $additional_data = array(
                'avatar' => 0 ,
                'full_name'  => $google_user['openid_ext1_value_firstname'] . ' ' . $google_user['openid_ext1_value_lastname'],                  
                'phone'      => '',
            );
            if($this->CI->ion_auth->register($username, $password, $email, $additional_data)){                
                $this->CI->ion_auth->trigger_events('pre_login');
                $user = $this->CI->user_model->get_user_by_email( $email );         
                $this->CI->ion_auth->set_session($user);
                $this->CI->ion_auth->update_last_login($user->id);
                $this->CI->ion_auth->clear_login_attempts($email);
                $this->CI->ion_auth->trigger_events(array('post_login', 'post_login_successful'));
                
                //send mail to member
                $this->CI->load->library('send_mail');                
                $user->password = $password;                 
                $data_email = array(
                    'data' => $user ,
                    'subject' => 'Thông tin tài khoản tại myprints.vn',
                    'mail_to' => $user->email ,
                    'view' => 'signup_social' ,                    
                );
               
                $this->CI->send_mail->send_mail($data_email);
                return $user->id;             
            }
            else{
                return 0;
            }
        }
    }
    
    
    public function yahoo_login_validate($yh_user){
        
    }
}